<?php
namespace common\records;
use Yii;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
use yii\behaviors\TimestampBehavior;

class UserInfo extends ActiveRecord implements IdentityInterface
{
    /**
    ** @return string 返回该AR类关联的数据表名
    **/
    public static function tableName()
    {
        return 'user_info';
    }

    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
            ];
    }

    public function scenarios()
    {
        $scenarios = parent::scenarios();
        return $scenarios;
    }
    /**
       * {@inheritdoc}
     */
    public function rules()
    {
        return [
            ['openid', 'string'],
            ['openidgzh', 'string'],
            ];
    }

    public function attributeLabels()
    {
        return [
            'uid' => '用户ID',
            'openid' => '微信UID',
            'photo' => '头像',
            'nick' => '昵称',
            'updated_at' => '最后登录时间',
            'created_at' => '创建时间',
            'coin' => '娃娃币数',
            'access_token' => '鉴权token',
            'expired_at' => 'token过期时间',
            'country' => '国家',
            'city' => '城市',
            'province' => '省份',
            'gender' => '性别',
            'role' => '测试人员',
                ];
    }

    /**
     * {@inheritdoc}
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id]);
    }

    /**
      * {@inheritdoc}
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::find()->where(['access_token' => $token])->andWhere(['>', 'expired_at', time()])->one();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->authKey;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return true;
    }

    /**
     * Validates password
     *
     * @param  string  $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return true;
    }
    public static function findByUnionid($unionid)
    {
        return static::find()->where(['unionid' => $unionid])->one();
    }
    public static function findByOpenid($openid)
    {
        return static::find()->where(['openid' => $openid])->one();
    }
    public function generateAccessToken()
    {
        $this->access_token = Yii::$app->security->generateRandomString();
        $this->expired_at = time() + 60 * 60 * 24 * 30;
    }
}
